#ifndef _MAX31865_h_
#define _MAX31865_h_

#include "sysinit.h"

#define MAX31865_SCK_PORT_PIN GPIO_PORT_P3,GPIO_PIN3
#define MAX31865_MISO_PORT_PIN GPIO_PORT_P3,GPIO_PIN2
#define MAX31865_MOSI_PORT_PIN GPIO_PORT_P6,GPIO_PIN0
#define MAX31865_CS_PORT_PIN GPIO_PORT_P6,GPIO_PIN1
#define MAX31865_RDY_PORT_PIN GPIO_PORT_P4,GPIO_PIN0

// 位带操作

#define MAX31865_SCK BITBAND_PERI(P3OUT, 3)
#define MAX31865_MISO BITBAND_PERI(P3IN, 2)
#define MAX31865_MOSI BITBAND_PERI(P6OUT, 0)
#define MAX31865_CS BITBAND_PERI(P6OUT, 1)
#define MAX31865_RDY BITBAND_PERI(P4IN, 0)

#define MAX31865_MOSI_HIGH (MAX31865_MOSI = 1)
#define MAX31865_MOSI_LOW (MAX31865_MOSI = 0)
#define MAX31865_SCK_HIGH (MAX31865_SCK = 1)
#define MAX31865_SCK_LOW (MAX31865_SCK = 0)
#define MAX31865_CS_HIGH (MAX31865_CS = 1)
#define MAX31865_CS_LOW (MAX31865_CS = 0)
#define READ_MAX31865_MISO MAX31865_MISO

#define MAX31856_CONFIG_REG 0x00
#define MAX31856_CONFIG_BIAS 0x80
#define MAX31856_CONFIG_MODEAUTO 0x40
#define MAX31856_CONFIG_MODEOFF 0x00
#define MAX31856_CONFIG_1SHOT 0x20
#define MAX31856_CONFIG_3WIRE 0x10
#define MAX31856_CONFIG_24WIRE 0x00
#define MAX31856_CONFIG_FAULTSTAT 0x02
#define MAX31856_CONFIG_FILT50HZ 0x01
#define MAX31856_CONFIG_FILT60HZ 0x00

#define MAX31856_RTDMSB_REG 0x01
#define MAX31856_RTDLSB_REG 0x02
#define MAX31856_HFAULTMSB_REG 0x03
#define MAX31856_HFAULTLSB_REG 0x04
#define MAX31856_LFAULTMSB_REG 0x05
#define MAX31856_LFAULTLSB_REG 0x06
#define MAX31856_FAULTSTAT_REG 0x07

#define MAX31865_FAULT_HIGHTHRESH 0x80
#define MAX31865_FAULT_LOWTHRESH 0x40
#define MAX31865_FAULT_REFINLOW 0x20
#define MAX31865_FAULT_REFINHIGH 0x10
#define MAX31865_FAULT_RTDINLOW 0x08
#define MAX31865_FAULT_OVUV 0x04

#define RTD_A 3.9083e-3
#define RTD_B -5.775e-7

typedef enum max31865_numwires
{
  MAX31865_2WIRE = 0,
  MAX31865_3WIRE = 1,
  MAX31865_4WIRE = 0
} max31865_numwires_t; // ����ģʽö�ٶ���

void MAX31865_Init(void);
void setWires(max31865_numwires_t wires); // RTD����ģʽ����
void autoConvert(unsigned char b);        // �����Զ�ת��ģʽ
void enableBias(unsigned char b);         // ʹ��ƫִ��ѹ

u8 readRegister8(u8 addr);                      // ���Ĵ�����8λ
u16 readRegister16(u8 addr);                    // �������Ĵ�����16λ
void readRegisterN(u8 addr, u8 buffer[], u8 n); // ��N���Ĵ���

void writeRegister8(u8 addr, u8 dat); // ָ���Ĵ���д8λ����

u16 MAX31865_Get_ADC(void);                                      // RTD���ݶ�ȡ

void clearFault(void); // ������ϱ�־λ
u8 MAX31865(u8 spi_cs, u8 spi_mosi, u8 spi_miso, u8 spi_clk);


uint8_t MAX31865_SB_Read(uint8_t addr);
void MAX31865_SB_Write(uint8_t addr, uint8_t wdata);

#endif
